package com.crazy.mybatis.gerenator.service.xml;

import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.stereotype.Component;

import com.crazy.mybatis.gerenator.service.Context;
import com.crazy.mybatis.gerenator.service.common.ElementName;

@Component
public class UpdateSelectiveBuilder extends AbstractElementBuilder implements ElementBuilder {

	private static final String DEFAULT_ID = "updateByPrimaryKeySelective";

	public UpdateSelectiveBuilder() {
		this(DEFAULT_ID, ElementName.UPDATE);
	}
	
	public UpdateSelectiveBuilder(String id) {
		this(id, ElementName.UPDATE);
	}

	UpdateSelectiveBuilder(String id, String elementName) {
		super(id, elementName);
	}

	@Override
	public Element build(Context context) {
		Element update = DocumentHelper.createElement(this.elementName);
		update.addAttribute("id", this.id);
		update.addAttribute("parameterType", context.getAbsoluteModel());
		update.addText(intent(2) + "UPDATE " + context.getTableName());

		Element set = update.addElement("set");
		buildChildrenElement(set, context);
		String pk = context.getPrimaryKey();
		update.addText(new StringBuilder()
				.append(intent(2))
				.append("WHERE ")
				.append(pk)
				.append(" = #{")
				.append(context.getColumnPropertyMap().get(pk))
				.append("}").toString());
		return update;
	}

	/*
	 * 循环构造 
	 *  <if test="id != null">
     *  	id,
     *	</if>
	 */
	private void buildChildrenElement(Element set, Context context) {
		for (String column : context.getColumnList()) {
			if (column.equals(context.getPrimaryKey())) {
				continue;
			}
			Element ifElement = set.addElement("if");
			ifElement.addAttribute("test", context.getColumnPropertyMap().get(column) + " != null");
				ifElement.setText(new StringBuilder(intent(4)).append(column)
						.append(" = #{")
						.append(context.getColumnPropertyMap().get(column))
						.append(", jdbcType=")
						.append(context.getColumnJdbcTypeMap().get(column))
						.append("},").toString());
		}
	}
}
